<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
            v-model="queryParams.userName"
            class="list-input"
            placeholder="搜索用户名称、手机号码"
            @input="handleSearchInput"
            @confirm="handleSearch"
        />
        <uni-icons
            v-if="queryParams.userName"
            type="clear"
            size="16"
            color="#999"
            @click="handleClear">
        </uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 高级筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>

        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">手机号码</text>
            <uni-easyinput
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                :clearable="true">
            </uni-easyinput>
          </view>

          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect
                v-model="queryParams.status"
                :options="statusOptions"
                value-field="value"
                label-field="text"
                placeholder="请选择状态"
                title="选择状态"/>
          </view>

          <view class="list-filter-item">
            <text class="list-filter-label">创建时间</text>
            <uni-datetime-picker
                v-model="queryParams.createTime"
                type="daterange"
                placeholder="选择时间范围"
                :clearIcon="true">
            </uni-datetime-picker>
          </view>

          <view class="list-filter-item">
            <text class="list-filter-label">所属部门</text>
            <BottomTreeSelect
                v-model="queryParams.deptId"
                :tree-data="deptTreeData"
                value-field="deptId"
                label-field="deptName"
                children-field="children"
                placeholder="请选择部门"
                title="选择部门"/>
          </view>
        </view>

        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:user:add'])">
        <uni-icons type="plus" size="14" color="#007aff"></uni-icons>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"></uni-icons>
        <text>刷新</text>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="list-content">
      <view
          v-for="user in userList"
          :key="user.userId"
          class="list-item"
          @click="handleView(user)">

        <view class="list-avatar" @click.stop>
          <ImagePreview
              :src="user.avatar"
              :width="80"
              :height="80"
              border-radius="50%"
              :preview="true"
              :visible="previewVisible && currentPreviewUser?.userId === user.userId"
              @open="handleAvatarPreview(user)"
              @close="closeAvatarPreview"
          />
        </view>

        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ user.userName }}</text>
            <text class="list-subtitle">{{ user.nickName }}</text>
            <view class="status-badge" :class="getUserStatusClass(user)">
              {{ getUserStatusText(user) }}
            </view>
          </view>

          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="person" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ user.dept?.deptName || '暂无部门' }}</text>
            </view>

            <view class="detail-item">
              <uni-icons type="phone" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ user.phonenumber || '-' }}</text>
            </view>

            <view class="detail-item">
              <uni-icons type="email" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ user.email || '-' }}</text>
            </view>

            <view class="detail-item">
              <uni-icons type="person" size="14" color="#999"></uni-icons>
              <DictTag :options="sys_user_sex" :value="user.sex" size="mini"/>
            </view>

            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ parseTime(user.createTime, '{y}-{m}-{d}') }}</text>
            </view>
          </view>
        </view>

        <view class="list-actions" v-if="user.userName !== 'admin'">
          <view class="action-btn action-primary" @click.stop="handleEdit(user)"
                v-if="checkPermission(['system:user:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"></uni-icons>
            <text class="action-text">编辑</text>
          </view>
          <view
              class="action-btn"
              :class="user.status === '0' ? 'action-warning' : 'action-success'"
              @click.stop="handleChangeStatus(user)"
              v-if="checkPermission(['system:user:edit'])">
            <uni-icons :type="user.status === '0' ? 'close' : 'checkmarkempty'" size="14"
                       :color="user.status === '0' ? '#ff9500' : '#34c759'"></uni-icons>
            <text class="action-text">{{ user.status === '0' ? '停用' : '启用' }}</text>
          </view>
          <view class="action-btn action-default" @click.stop="handleResetPassword(user)"
                v-if="checkPermission(['system:user:resetPwd'])">
            <uni-icons type="reload" size="14" color="#666"></uni-icons>
            <text class="action-text">重置</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(user)"
                v-if="checkPermission(['system:user:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"></uni-icons>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="userList.length > 0" class="list-load-more">
      <uni-load-more
          :status="loadStatus"
          :content-text="loadText"
          @clickLoadMore="handleLoadMore">
      </uni-load-more>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && userList.length === 0" class="list-empty">
      <uni-icons type="person" size="48" color="#ddd"></uni-icons>
      <text class="list-empty-text">暂无用户数据</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['system:user:add'])">添加用户</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {changeUserStatus, delUser, listUser, resetUserPwd} from '@/api/system/user'
import {handleTree, parseTime} from '@/utils/ruoyi'
import {listDept} from '@/api/system/dept'
import {BottomSelect, BottomTreeSelect} from '@/components/select'
import {useDict} from '@/utils/dict'
import DictTag from '@/components/DictTag'
import {usePermission} from '@/utils/permission'
import ImagePreview from '@/components/ImagePreview/index.vue'

const {proxy} = getCurrentInstance()
const checkPermission = usePermission()

// 字典数据
const {sys_user_sex} = useDict('sys_user_sex')

// 数据定义
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const deptTreeData = ref([])
const filterPopup = ref(null)

// 头像预览相关
const previewVisible = ref(false)
const currentPreviewUser = ref(null)

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: '',
  deptId: '',
  createTime: ''
})

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
]

// 页面加载
onMounted(() => {
  getList()
  loadDeptTree()
})

// 获取用户列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listUser(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        userList.value = newData
      } else {
        userList.value.push(...newData)
      }

      total.value = response.total || 0

      if (userList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    proxy.$modal.showToast('获取用户列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 加载部门树
async function loadDeptTree() {
  try {
    const response = await listDept()
    if (response.code === 200) {
      deptTreeData.value = handleTree(response.data, 'deptId', 'parentId', 'children')

      // 数据加载后，若已有选中的部门ID，组件会根据 v-model 展示选项，无需额外处理
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
  }
}


// 获取用户状态样式类
function getUserStatusClass(user) {
  return user.status === '0' ? 'status-normal' : 'status-disabled'
}

// 获取用户状态文本
function getUserStatusText(user) {
  return user.status === '0' ? '正常' : '停用'
}


// 事件处理
let searchTimer = null

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.userName = ''
  handleQuery()
}

function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter()
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    userName: '',
    phonenumber: '',
    status: '',
    deptId: '',
    createTime: ''
  })
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}


// 查询
function handleQuery() {
  queryParams.pageNum = 1
  userList.value = []
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: './edit?mode=add'
  })
}

function handleEdit(user) {
  uni.navigateTo({
    url: `./edit?mode=edit&userId=${user.userId}`
  })
}

function handleView(user) {
  uni.navigateTo({
    url: `./edit?mode=view&userId=${user.userId}`
  })
}

async function handleChangeStatus(user) {
  try {
    const newStatus = user.status === '0' ? '1' : '0'
    const statusText = newStatus === '0' ? '启用' : '停用'

    await proxy.$modal.confirm(`确认要${statusText}用户"${user.userName}"吗？`)

    const response = await changeUserStatus(user.userId, newStatus)
    if (response.code === 200) {
      user.status = newStatus
      proxy.$modal.showToast(`${statusText}成功`)
    }
  } catch (error) {
    console.error('修改状态失败:', error)
  }
}

async function handleResetPassword(user) {
  try {
    await proxy.$modal.confirm(`确认要重置用户"${user.userName}"的密码吗？`)

    const response = await resetUserPwd(user.userId, '123456')
    if (response.code === 200) {
      proxy.$modal.showToast('重置成功，新密码是：123456')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

async function handleDelete(user) {
  try {
    await proxy.$modal.confirm(`确认要删除用户"${user.userName}"吗？`)

    const response = await delUser(user.userId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除用户失败:', error)
  }
}

function handleRefresh() {
  handleQuery()
}

// 头像预览相关方法
function handleAvatarPreview(user) {
  if (!user.avatar) return
  currentPreviewUser.value = user
  previewVisible.value = true
}

function closeAvatarPreview() {
  previewVisible.value = false
  currentPreviewUser.value = null
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>